package org.simple.framework.html.parser.convert;

/**
 * 项目名称：simple-framework
 * 类名称：TypeChainConverter
 * 类描述：TypeChainConverter
 * 创建时间：2018/9/25
 *
 * @author sisyphus   (E-mail:1620657419@qq.com)
 * @version v1.0
 */
public class TypeChainConverter implements TypeConverter {

    private TypeConverter typeConverter;

    private TypeChainConverter nextConverter;

    private TypeChainConverter(TypeConverter typeConverter) {
        this.typeConverter = typeConverter;
    }

    public static TypeChainConverter build(TypeConverter typeConverter) {
        return new TypeChainConverter(typeConverter);
    }

    @Override
    public boolean isSupported(Class clazz) {
        if (typeConverter.isSupported(clazz)) {
            return true;
        } else {
            return nextConverter != null && nextConverter.isSupported(clazz);
        }
    }

    @Override
    public Object convert(Object o, Class clazz) {
        if (typeConverter.isSupported(clazz)) {
            return typeConverter.convert(o, clazz);
        }
        return nextConverter == null ? null : nextConverter.convert(o, clazz);
    }

    public TypeChainConverter next(TypeConverter typeConverter) {
        this.nextConverter = new TypeChainConverter(typeConverter);
        return nextConverter;
    }

    public TypeChainConverter next(TypeChainConverter nextConverter) {
        this.nextConverter = nextConverter;
        return nextConverter;
    }

}
